package com.dynamo.transport.network.practise.bio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

/**
 * @author duanyimiao
 * @create 2018-10-25 11:02 PM
 * @description 底层数据传输服务一直监听连接，并等待数据到来
 **/
public class Server {

    private String host;
    private int bindPort;
    private ServerSocket serverSocket;
    private InetSocketAddress socketAddress;
    private ChannelHandler channelHandler;
private ExecutorService executors;
    public Server(String host, int bindPort) {
        this.host = host;
        this.bindPort = bindPort;
        socketAddress = new InetSocketAddress(host, bindPort);
        //注意，这里的线程池中的线程个数必须大于client个数，因为连接上的client哪怕没有发送数据时该线程也会阻塞起来等待可读数据到来，该线程一直被该client使用
        executors = new ThreadPoolExecutor(1, 1,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(10));
        //初始化数据
        init();
    }

    private void init() {
        try {
            serverSocket = new ServerSocket();

        } catch (Exception e) {
            //TODO 使用logback记录日志
            e.printStackTrace();
        }
    }

    public void channelHandler(ChannelHandler channelHandler) {
        this.channelHandler = channelHandler;
    }

    /**
     * 启动底层传输数据服务
     */
    public void start() throws IOException {
        serverSocket.bind(socketAddress);
        acceptConnect();
    }

    public void acceptConnect() {
        while (true) {
            try {
                Socket socket = serverSocket.accept();
                SocketThread socketThread = new SocketThread(socket, channelHandler);
                executors.execute(socketThread);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
